package com.ruoyi.user.app;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.GCMParameterSpec;
import java.security.SecureRandom;
import java.util.Base64;

public class SecreateApp {
    private static final String ALGORITHM = "AES";
    private static final String TRANSFORMATION = "AES/GCM/NoPadding";
    private static final int AES_KEY_SIZE = 256; // AES-256
    private static final int GCM_NONCE_LENGTH = 12; // 12 bytes IV
    private static final int GCM_TAG_LENGTH = 16; // 128 bits authentication tag

    public static String getSecreate( String sensitiveData )throws Exception {
        // 生成AES密钥
        KeyGenerator keyGenerator = KeyGenerator.getInstance(ALGORITHM);
        keyGenerator.init(AES_KEY_SIZE);
        SecretKey secretKey = keyGenerator.generateKey();

        // 生成GCM的IV
        byte[] iv = new byte[GCM_NONCE_LENGTH];
        SecureRandom random = new SecureRandom();
        random.nextBytes(iv);

        // 加密
        /*  String sensitiveData = "123";*/
        Cipher cipher = Cipher.getInstance(TRANSFORMATION);
        GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(GCM_TAG_LENGTH * 8, iv);
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, gcmParameterSpec);
        byte[] encryptedBytes = cipher.doFinal(sensitiveData.getBytes());
        String encryptedData = Base64.getEncoder().encodeToString(encryptedBytes);
        System.out.println("Encrypted data: " + encryptedData);
        return  encryptedData;

    /*    // 解密
        cipher.init(Cipher.DECRYPT_MODE, secretKey, gcmParameterSpec);
        byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedData));
        String decryptedData = new String(decryptedBytes);
        System.out.println("Decrypted data: " + decryptedData);*/
    }
}

